import React, { Component } from 'react';
import { Modal, Cascader, Input, Row, Col, DatePicker, Form, Select, Upload, Icon,  message } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ActivityProductTable from './ActivityProductTable';
import divisions from '../../utils/divisions.json';
import * as check from '../../utils/checkLib';
import styles from './ActivityProducts.less';

moment.locale('zh-cn');

const Option = Select.Option;
const FormItem = Form.Item;

function toString(str, type) {
  if (typeof str !== 'undefined' && str !== null) {
    return str.toString();
  }
  if (type === 'SELECT') return undefined;
  return '';
}

class ActivityListModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      previewImage: '',
      picList: null,
      previewVisible: false,
    };

    // skuTable改写父级方法
    this.getSkuValue = null;
    this.clearSkuValue = null;
  }

  handleSubmit() {
    const p = this;
    const { form, dispatch, modalValues = {} } = p.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) { return; }
        
      	
      p.getSkuValue((activityDetailListTemp) => {
				const values = {
          	...fieldsValue,
	          activityStart: fieldsValue.activityStart && fieldsValue.activityStart.format('YYYY-MM-DD'),
        		activityEnd: fieldsValue.activityEnd && fieldsValue.activityEnd.format('YYYY-MM-DD'),
        };
      	// 处理图片
        if (values.activityMainPic) {
          const uploadMainPic = [];
          const mainPicNum = values.mainPicNum;
          values.activityMainPic.forEach((el, index) => {
            uploadMainPic.push({
              type: el.type,
              uid: `i_${index}`,
              url: el.url || el.response.data,
            });
          });
          values.activityMainPic = JSON.stringify({ picList: uploadMainPic, mainPicNum });
        }

        if (modalValues.data) {
          dispatch({
            type: 'activity/updateActivity',
            payload: { ...values, id: modalValues.data.id, activityDetailsList: JSON.stringify(activityDetailListTemp) },
          });
        } else {
          dispatch({
            type: 'activity/addActivity',
            payload: { ...values, activityDetailsList: JSON.stringify(activityDetailListTemp) },
          });
        }
        p.closeModal();
      });
    });
  }

  closeModal() {
    const { form, close } = this.props;
    form.resetFields();
    close();
    // 清理skuTable
    setTimeout(() => {
      this.clearSkuValue();
    }, 100);
  }

	handleCancel() {
    this.setState({ previewVisible: false });
  }

	checkMainPicNum(rules, value, cb) {
    if (this.props.form.getFieldValue('activityMainPic').length > 0 && !value) {
      cb(new Error('请选择主图'));
    } else cb();
  }

  checkImg(rules, values, cb) { cb(); }

  handleDelete(id) {
    const { skuList } = this.state;
    const skuData = skuList.filter(item => id !== item.id);
    this.setState({ skuList: skuData });
  }

  render() {
    const p = this;
    const { form, title, visible, modalValues = {}, agencyList = [] } = p.props;
    const { previewVisible, previewImage } = this.state;
    const activityData = (modalValues && modalValues.data) || {};
    const { getFieldDecorator } = form;
    const modalProps = {
      visible,
      width: 900,
      wrapClassName: 'modalStyle',
      okText: '保存',
      title,
      maskClosable: false,
      closable: true,
      onOk() {
        p.handleSubmit();
      },
      onCancel() {
        p.closeModal();
      },
    };

    const formItemLayout = {
      labelCol: { span: 11 },
      wrapperCol: { span: 13 },
    };

		// 图片字符串解析
    let mainPicNum;
    let picList = [];
    if (modalValues.data && modalValues.data.activityMainPic) {
      const picObj = JSON.parse(modalValues.data.activityMainPic);
      mainPicNum = toString(picObj.mainPicNum, 'SELECT') || '1';
      picList = picObj.picList || [];
    }

    const uploadProps = {
      action: '/haierp1/uploadFile/picUpload',
      listType: 'picture-card',
      multiple: true,
      data(file) {
        return {
          pic: file.name,
        };
      },
      beforeUpload(file) {
        const isImg = file.type === 'image/jpeg' || file.type === 'image/bmp' || file.type === 'image/gif' || file.type === 'image/png';
        if (!isImg) { message.error('请上传图片文件'); }
        return isImg;
      },
      name: 'pic',
      onPreview(file) {
        p.setState({
          previewVisible: true,
          previewImage: file.url || file.thumbUrl,
        });
      },
      onChange(info) {
        if (info.file.status === 'done') {
          if (info.file.response && info.file.response.success) {
            message.success(`${info.file.name} 成功上传`);
            // 添加文件预览
            const newFile = info.file;
            newFile.url = info.file.response.data;
          } else { message.error(`${info.file.name} 解析失败：${info.file.response.msg || info.file.response.errorMsg}`); }
        } else if (info.file.status === 'error') { message.error(`${info.file.name} 上传失败`); }
        // 主图选项增删联动
        const fileList = p.state.picList || [];
        const newFileList = info.fileList;
        const selectedMainPicNum = p.props.form.getFieldValue('mainPicNum');
        if (newFileList.length === 1 || (newFileList.length < fileList.length && selectedMainPicNum > newFileList.length)) {
          p.props.form.setFieldsValue({ mainPicNum: '1' });
        }
        p.setState({ picList: info.fileList });
      },
    };

    const fileListSource = this.state.picList || picList;
    return (
      <Modal {...modalProps} className={styles.modalStyle}>
        <Form onSubmit={p.handleSubmit.bind(p)}>
          <Row gutter={10}>
          	<Col span={8}>
              <FormItem
                label="活动编号"
                {...formItemLayout}
              >
                {getFieldDecorator('activityNo', {
                  initialValue: activityData.activityNo,
                })(
                  <Input placeholder={!activityData.activityNo && '自动生成'} disabled />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label="活动名称"
                {...formItemLayout}
              >
                {getFieldDecorator('activityName', {
                  initialValue: activityData.activityName,
                  rules: [{ required: true, message: '请输入活动名称'}],
                })(
                  <Input placeholder="请输入活动名称" />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label="活动描述"
                {...formItemLayout}
              >
                {getFieldDecorator('activityDesc', {
                  initialValue: activityData.activityDesc,
                  rules: [{ required: true, message: '请输入活动描述'}],
                })(
                  <Input placeholder="请输入活动描述" />,
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={10}>
          	<Col span={8}>
              <FormItem
                label="活动开始时间"
                {...formItemLayout}
              >
                {getFieldDecorator('activityStart', {
                  initialValue: (activityData.activityStart && moment(activityData.activityStart, 'YYYY-MM-DD HH:mm:ss')) || moment(new Date(), 'YYYY-MM-DD HH:mm:ss'),
                  rules: [{ required: true, message: '请输入活动开始时间' }],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请输入活动开始时间" />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label="活动结束时间"
                {...formItemLayout}
              >
                {getFieldDecorator('activityEnd', {
                  initialValue: (activityData.activityEnd && moment(activityData.activityEnd, 'YYYY-MM-DD HH:mm:ss')),
                  rules: [{ required: true, message: '请输入活动结束时间' }],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请输入活动结束时间" />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={10}>
							<Col>
                  <FormItem
                    label="添加活动图片"
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    style={{ marginRight: '-20px' }}
                  >
                    {getFieldDecorator('activityMainPic', {
                      initialValue: picList,
                      valuePropName: 'fileList',
                      getValueFromEvent(e) {
                        if (!e || !e.fileList) {
                          return e;
                        }
                        const { fileList } = e;
                        return fileList;
                      },
                      rules: [{ validator: this.checkImg.bind(this) }],
                    })(
                      <Upload {...uploadProps}>
                        <Icon type="plus" className={styles.uploadPlus} />
                        <div className="ant-upload-text">上传图片</div>
                      </Upload>,
                    )}

                    <Modal visible={previewVisible} title="预览图片" footer={null} onCancel={this.handleCancel.bind(this)}>
                      <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                {fileListSource.length > 0 && <Col span={7}>
                  <FormItem
                    label="选择主图"
                    {...formItemLayout}
                  >
                    {getFieldDecorator('mainPicNum', {
                      initialValue: mainPicNum,
                      rules: [{ validator: this.checkMainPicNum.bind(this) }],
                    })(
                      <Select placeholder="请选择主图" allowClear>
                        {fileListSource.map((el, index) => (
                          <Option key={index} value={(index + 1).toString()}>{`图片${index + 1}`}</Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>}
          </Row>
          <Row>
            <Col>
              <FormItem
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 18 }}
              >
                {getFieldDecorator('remark', {
                  initialValue: activityData.remark,
                })(
                  <Input placeholder="请输入备注信息" size="large" style={{ marginLeft: 3, width: 646 }} />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <ActivityProductTable modalValues={activityData} dcTitle={p.props.title} data={activityData.activityDetails} parent={this} />
          </Row>
        </Form>
      </Modal>
    );
  }
}

export default Form.create()(ActivityListModal);
